import React, {useState} from "react"
import {Upload} from "antd"
import {read} from "zr-react-toolbox"
import LoadingOutlined from "@ant-design/icons/es/icons/LoadingOutlined"
import PlusOutlined from "@ant-design/icons/lib/icons/PlusOutlined"
import getBase64 from "../image_ase64"
import PropTypes from 'prop-types'

const calUrl = (url, value, valueToUrl) => {
  if (url) return url;
  if (valueToUrl && value) {
    return valueToUrl(value)
  }
  return undefined
}

const SingleImageUploader = (props) => {
  const [serverFile, $serverFile] = useState({})
  const [url, $url] = useState()
  const [loading, $loading] = useState(false)

  const {onChange, valueToUrl, text, value, ...inherit} = props

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined/> : <PlusOutlined/>}
      <div className="ant-upload-text">{text || '上传封面'}</div>
    </div>
  )

  const onFileChange = (info) => {
    $loading(info.file.status === 'uploading')
    if (info.file.status === 'done') {
      const serverFileRecord = read(info, 'file.response.data')
      $serverFile(serverFileRecord)
      onChange(serverFileRecord)
      //TODO:after change exist picture 删除已有的图片
      getBase64(info.file.originFileObj, (url) => {
        $loading(false)
        $url(url)
      })
    }
  }


  const iUrl = calUrl(url, value, valueToUrl)
  return (
    <Upload
      {...inherit}
      accept={'image/* '}
      multiple={false}
      withCredentials={true}
      listType="picture-card"
      showUploadList={false}
      onChange={onFileChange}
    >
      {iUrl ? <img src={iUrl} alt="avatar" style={{width: '100%'}}/> : uploadButton}
    </Upload>
  )
}

SingleImageUploader.propTypes = {
  /**上传服务器地址*/
  action: PropTypes.string.isRequired,
  /**设置值,一般为已有图片id*/
  value: PropTypes.string,
  /**通过值铆取一个已有图片地址函数*/
  valueToUrl: PropTypes.func,
  /**上传按钮文字*/
  text: PropTypes.string,
  /**上传按钮组件*/
  //uploadButton: PropTypes.func

}

//单张图片上传
export default SingleImageUploader